package com.roadjava.javaweb.student.servlet;

import com.roadjava.javaweb.student.beans.entity.AdminDO;
import com.roadjava.javaweb.student.service.AdminService;
import com.roadjava.javaweb.student.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "loginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        if ("trueLogin".equals(type)) { // 执行登录的
            String userName = request.getParameter("userName");
            String pwd = request.getParameter("pwd");
            if (userName == null || "".equals(userName.trim())
                || pwd == null || "".equals(pwd.trim())) {
                request.setAttribute("message","用户名或密码不能为空");
                request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request,response);
                return;
            }
            AdminService adminService = new AdminServiceImpl();
            AdminDO adminDO = adminService.validateLogin(userName);
            if (adminDO != null && pwd.equals(adminDO.getPwd())) {
                // 放到session之前情况敏感信息
                adminDO.setPwd(null);
                request.getSession().setAttribute("admin",adminDO);
                // 当我们做了提交表单的动作后再通过getRequestDispatcher进行内部转发，
                // 刷新页面会导致表单的重复提交
                response.sendRedirect(request.getContextPath()+"/studentServlet?type=toStudentManage"); // 重定向
            }else {
                request.setAttribute("message","用户名或密码不正确");
                request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request,response);
            }
        }else {
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request,response);
        }
    }
}
